package com.tanhua.recommend.listeners;

import com.alibaba.fastjson.JSON;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.mongo.VideoScore;
import org.bson.types.ObjectId;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class RecommendVideoListener {

    @Autowired
    private MongoTemplate mongoTemplate;

    @RabbitListener(
            bindings= @QueueBinding(
                    value = @Queue(
                            name = "tanhua.video.queue",
                            durable = "true"
                    ),
                    exchange = @Exchange(
                            name = "tanhua.log.exchange",
                            type = ExchangeTypes.TOPIC
                    ),
                    key = "log.video"
            )
    )
    //0301为发小视频，0302为小视频点赞，0303为小视频取消点赞，0304为小视频评论
    public void recommend(String message) {
        System.out.println("读取视频日志="+message);
        Map<String,String> map = JSON.parseObject(message, Map.class);
        //1、获取消息数据  （用户id，操作类型，业务ID）
        Long userId = Long.valueOf(map.get("userId"));
        String type = map.get("type");
        String videoId = map.get("busId"); //动态id
        //2、构造评分数据  VideoScore对象
        //根据视频id，查询Video对象  -->  vid
        Video video = mongoTemplate.findById(new ObjectId(videoId), Video.class);
        if(video != null) {
            VideoScore vs = new VideoScore();
            vs.setUserId(userId);
            vs.setVideoId(video.getVid());
            vs.setDate(System.currentTimeMillis());
            Double score = getScore(type);
            vs.setScore(score);
            mongoTemplate.save(vs);
        }

    }

    private static Double getScore(String type) {
        //0301为发小视频，0302为小视频点赞，0303为小视频取消点赞，0304为小视频评论
        Double score = 0d;
        switch (type) {
            case "0301":
                score=2d;
                break;
            case "0302":
                score=5d;
                break;
            case "0303":
                score = -5d;
                break;
            case "0304":
                score = 10d;
                break;
            default:
                break;
        }
        return score;
    }


}
